import { DirectiveBinding } from 'vue';
import { useUserStore } from '@/store';

export function checkPermission(code: string){
  const userStore = useUserStore();
  const { permCodes } = userStore;
  return permCodes.includes(code)
}
//登录用户的角色的权限控制逻辑，通过资源配置的permCode控制
function checkRolePermission(el: HTMLElement, binding: DirectiveBinding) {
  const { value } = binding;

  if (value) {
    const hasPermission = checkPermission(value);
    if (!hasPermission && el.parentNode) {
      el.parentNode.removeChild(el);
    }
  } else {
    throw new Error(`need roles! Like v-role="'label.manage'"`);
  }
}

export default {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkRolePermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkRolePermission(el, binding);
  },
};
